home *** CD-ROM | disk | FTP | other *** search
- Path: news.microsoft.com!news
- From: a-cnadc@microsoft.com (Dann Corbit)
- Newsgroups: comp.lang.c
- Subject: Re: Recursion
- Date: 6 Apr 1996 03:06:40 GMT
- Organization: Microsoft Corporation
- Message-ID: <4k4n40$tbi@news.microsoft.com>
- References: <31624BC2.70D2@sooner.net> <828548265snz@genesis.demon.co.uk> <4k10q0$m5d@linet06.li.net>
- NNTP-Posting-Host: 157.57.171.202
- Mime-Version: 1.0
- X-Newsreader: WinVN 0.93.14
-
- In article <4k10q0$m5d@linet06.li.net>, jeremy@newshost.li.net says...
- >
- >Lawrence Kirby (fred@genesis.demon.co.uk) wrote:
- >
- >: I think you've picked a bad example. You really need an extra argument in
- >: this case to pass on a running accumulator. A more suitable problem would
- >: be to write a recursive function that is passed an integer (unsigned is
- >: easiest) and writes the character representation to stdout.
- >Absolutely WRONG. The whole point of recursion is that you do not need a
- >running accumulator. When written correctly, the return value of each
- >recursive loop will be the correct accumulated value. ANyhow, here is a
- >better version of what I already posted...
- >
- >#include <stdio.h>
- >#include <stdlib.h>
- >#include <string.h>
- >#include <math.h>
- >
- >int convert(char *string)
- > {
- > int value;
- > int len = strlen(string);
- >
- > if (string[0] == '\0')
- > return(0);
- > value = convert(string+1);
- > value += ((string[0] - '0') * pow(10,len-1));
- > return(value);
- > }
- >
- >void main()
- > {
- > char *string = "1234";
- >
- > printf("%d\n",convert(string));
- > }
-
- I have to agree, with Mr. Kirby that recursion is a most
- inelegant way to do this. Here is another ugly recursive
- solution. The elegant way is atoi(). Iterative is next
- best. Recursive is downright silly. But we all have our
- silly moments.
-
- #include <stdio.h>
- #include <ctype.h>
- #include <string.h>
-
- /* Notes:
- * 1. Clobbers input string.
- * 2. No error checking
- * 3. Plain old double-mugged ugly.
- */
- int convert( char *string )
- {
- int value = 0;
- /* Is there stuff in the string? */
- if ( *string )
- { /* Reverse it to deal with smallest digit first */
- strrev( string );
- if ( isdigit( *string ) ) /* Make sure digit is from 0 to 9 */
- {
- value = *string - '0'; /* calculate the value */
- }
- string++; /* Go to the next character */
- if ( *string ) /* if we still have more stuff, recurse */
- {
- strrev( string ); /* Reverse (n-1) chars back */
- value += 10*convert( string );
- }
- }
- return ( value );
- }
-
- void main( )
- {
- char *string = "1234";
-
- printf( "%d\n", convert( string ) );
- }
- --
- The opinions expressed in this message are my own personal views
- and do not reflect the official views of Microsoft Corporation.
- In fact, I'm just a subcontractor, not an employee, so pull in your claws.
-
-